package com.vim.common.shiro;

import com.vim.modules.web.model.SysUser;
import com.vim.modules.web.service.SysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

public class CustomRealm extends AuthorizingRealm {

    @Resource
    private SysUserService sysUserService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        SysUser sysUser = sysUserService.findLoginAccount(token.getUsername());
        if(null == sysUser){
            throw new AuthenticationException();
        }
        ByteSource credentialsSalt = ByteSource.Util.bytes(sysUser.getLoginAccount());
        return new SimpleAuthenticationInfo(sysUser, sysUser.getLoginPassword(), credentialsSalt, getName());
    }
}
